<!-- 线下商家入驻 -->
<template>
  <view class="openShop-page" v-if="page_show">
    <!-- 步骤条 -->
    <view class="bg-white padding">
      <view class="cu-steps">
        <view class="cu-item" :class="index > num ? '' : 'text-blue'" v-for="(item, index) in numList" :key="index" @tap="handleNav(index)">
          <text class="num" :data-index="index + 1"></text> {{ item.name }}
        </view>
      </view>
    </view>
    <!-- 第一步填写商户信息 -->
    <form v-show="num === 0">
      <view class="cu-form-group margin-top">
        <view class="title">店铺名称<text class="text-red">*</text></view>
        <input placeholder="请输入店铺名称(不可修改)" type="text" maxlength="12" v-model="info.name" />
      </view>
      <view class="cu-form-group">
        <view class="title">联系人<text class="text-red">*</text></view>
        <input placeholder="请输入联系人" type="text" maxlength="10" v-model="info.linkman" />
      </view>
      <view class="cu-form-group">
        <view class="title">联系方式<text class="text-red">*</text></view>
        <input placeholder="请输入联系方式" type="number" maxlength="13" v-model="info.linktel" />
      </view>
      <view class="cu-form-group">
        <view class="title">主营类目<text class="text-red">*</text></view>
        <picker @change="cateChange" :value="cindex" :range="cateArr" range-key="name">
          <view class="picker">{{ cateName }}</view>
        </picker>
      </view>

      <view class="cu-form-group">
        <view class="title">营业开始时间<text class="text-red">*</text></view>
        <picker mode="time" :value="info.start_hours" @change="startTimeChange">
          <view class="picker">
            {{ info.start_hours }}
          </view>
        </picker>
      </view>
      <view class="cu-form-group">
        <view class="title">营业结束时间<text class="text-red">*</text></view>
        <picker mode="time" :value="info.end_hours" @change="endTimeChange">
          <view class="picker">
            {{ info.end_hours }}
          </view>
        </picker>
      </view>

      <view class="cu-form-group">
        <view class="title">选择商家地址<text class="text-red">*</text></view>
        <!--地址三级联动-->
        <rf-pick-regions :multiStrInversion="multiStr" @getRegions="handleGetRegions"> </rf-pick-regions>
      </view>
      <!-- <view class="cu-form-group" @tap="gotoMapNearby">
        <view class="title">商家定位<text class="text-red">*</text></view>
        <view class="cuIcon-locationfill"></view>
      </view> -->

      <view class="cu-form-group">
        <view class="title">详细地址</view>
        <input placeholder="请输入详细地址" type="text" v-model="info.address" />
      </view>
      <view class="cu-form-group">
        <view class="title">店铺简介</view>
      </view>
      <view class="cu-form-group align-start">
        <textarea maxlength="500" placeholder="请输入店铺简介" v-model="info.desc"></textarea>
      </view>
      <view class="rejectTips" v-if="rejectTips && BtnState === 2">
        <view class="title text-red">{{ rejectTips }}</view>
      </view>
    </form>
    <!-- 第二部上传资质-->
    <form v-show="num === 1">
      <!-- 营业执照+法人身份证 -->
      <view class="cu-bar bg-white margin-top">
        <view class="action"> 上传营业执照、法人身份证正反面 </view>
        <view class="action"> {{ zhengming.length }}/3 </view>
      </view>
      <view class="cu-form-group">
        <view class="grid col-3 grid-square flex-sub">
          <view class="bg-img" v-for="(item, index) in zhengming" :key="index" @tap="ViewImage('one', index)" :data-url="zhengming[index]">
            <image :src="zhengming[index]" mode="aspectFill"></image>
            <view class="cu-tag bg-red" @tap.stop="DelImg('one', index)" :data-index="index">
              <text class="cuIcon-close"></text>
            </view>
          </view>
          <view class="solids" @tap="ChooseImage('one', 3)" v-if="zhengming.length < 3">
            <text class="cuIcon-cameraadd"></text>
          </view>
        </view>
      </view>
      <view class="cu-bar bg-white">
        <view class="action">注：一个营业执照只能入驻一次线下商家。不可重复入驻。</view>
      </view>
      <!-- 门头照、店铺封面图 -->
      <view class="cu-bar bg-white margin-top">
        <view class="action"> 上传店铺封面图/门头照 </view>
        <view class="action"> {{ pic.length }}/1 </view>
      </view>
      <view class="cu-form-group">
        <view class="grid col-3 grid-square flex-sub">
          <view class="bg-img" v-for="(item, index) in pic" :key="index" @tap="ViewImage('two', index)" :data-url="pic[index]">
            <image :src="pic[index]" mode="aspectFill"></image>
            <view class="cu-tag bg-red" @tap.stop="DelImg('two', index)" :data-index="index">
              <text class="cuIcon-close"></text>
            </view>
          </view>
          <view class="solids" @tap="ChooseImage('two', 1)" v-if="pic.length < 1">
            <text class="cuIcon-cameraadd"></text>
          </view>
        </view>
      </view>
      <!-- 店铺实景图 -->
      <view class="cu-bar bg-white margin-top">
        <view class="action"> 上传店铺实景图 </view>
        <view class="action"> {{ pics.length }}/9 </view>
      </view>
      <view class="cu-form-group">
        <view class="grid col-3 grid-square flex-sub">
          <view class="bg-img" v-for="(item, index) in pics" :key="index" @tap="ViewImage('three', index)" :data-url="pics[index]">
            <image :src="pics[index]" mode="aspectFill"></image>
            <view class="cu-tag bg-red" @tap.stop="DelImg('three', index)" :data-index="index">
              <text class="cuIcon-close"></text>
            </view>
          </view>
          <view class="solids" @tap="ChooseImage('three', 9)" v-if="pics.length < 9">
            <text class="cuIcon-cameraadd"></text>
          </view>
        </view>
      </view>
    </form>
    <!-- 第三部确认签约 -->
    <form v-show="num === 2">
      <!-- 设置比例 -->
      <view class="cu-form-group">
        <view class="title">用户积分倍数(倍)</view>
        <picker @change="radioChange" :range="radioList" range-key="name">
          <view class="picker">{{ info.user_score_rate }}倍</view>
        </picker>
      </view>
      <view class="cu-form-group">
        <view class="title">商家让利比例(%)</view>
      </view>
      <view class="wrap bg-white">
        <u-slider v-model="info.ranglibili" min="4" max="51" blockSize="22" showValue class="slider"> </u-slider>
        <view class="sliderUnit">%</view>
      </view>

      <view class="cu-form-group margin-top">
        <view class="title">设置登录密码</view>
        <input placeholder="请输入登录密码" type="password" v-model="info.pwd" />
      </view>
      <view class="cu-form-group">
        <view class="title">确认登录密码</view>
        <input placeholder="请确认登录密码" type="password" v-model="info.repwd" />
      </view>
    </form>

    <view class="btn bg-white">
      <button class="cu-btn round lg flex1" v-if="num == 0 && BtnState === 0" disabled><text class="text-black">已申请，审核中</text></button>
      <button class="cu-btn round lg flex1" v-else-if="num == 0 && BtnState === 1" disabled><text class="text-black">已通过注册，无法重复注册</text></button>
      <button class="cu-btn bg-blue round lg flex1" v-else-if="num == 0 && BtnState === 2" @tap="handleNav(num + 1)">注册未通过，请重新注册</button>
      <button class="cu-btn bg-blue round lg flex1" v-else-if="num == 0 && BtnState !== 0 && BtnState !== 1" @tap="handleNav(num + 1)">下一步</button>
      <button class="cu-btn bg-blue round lg flex1" v-else-if="num == 1 && BtnState !== 0 && BtnState !== 1" @tap="handleNav(num + 1)">下一步</button>
      <button class="cu-btn bg-blue round lg flex1 margin-top" v-else-if="num === 2 && BtnState !== 0 && BtnState !== 1" @tap="handleSubmit">提交申请</button>
    </view>

    <loading v-show="loading"></loading>
  </view>
</template>

<script>
var app = getApp()
import rfPickRegions from '@/components/rf-pick-regions'
export default {
  components: { rfPickRegions },
  data() {
    return {
      page_show: false,
      loading: false,
      token: '',
      numList: [
        { cuIcon: 'usefullfill', name: '商家信息' },
        { cuIcon: 'radioboxfill', name: '上传资质' },
        { cuIcon: 'roundclosefill', name: '确认签约' }
      ],
      num: 0,
      imgList: [],
      info: {
        is_offline: 1, //固定传1
        linkman: '', //联系人
        linktel: '', //联系方式
        name: '', //店铺名称
        zhengming: '', //营业执照、法人信息[身份证正反面]
        pic: '', //店铺封面图
        pics: '', //门店实景图
        pwd: '', //密码
        repwd: '', //重复密码
        cid: 13, //分类
        latitude: '', //纬度
        longitude: '', //经度
        province: '', //省
        city: '', //市
        district: '', //区
        street: '', //街道
        address: '', //地址
        start_hours: '8:00', //开始时间
        end_hours: '21:00', //结束时间
        desc: '', //简介
        ranglibili: 4, //让利比例
        user_score_rate: 5 //积分倍数
      },
      zhengming: [],
      pic: [],
      pics: [],

      cindex: 0,
      cateArr: [],
      cateName: '',
      multiStr: '请选择省市区', //地址中文
      //地址
      addressData: {
        province_id: '', //省id
        city_id: '', //市id
        area_id: '', //区id
        street_id: '' //街道id
      },
      BtnState: null,
      rejectTips: '', //驳回提示
      radioList: [
        {
          name: '1倍',
          value: 1
        },
        {
          name: '2倍',
          value: 2
        },
        {
          name: '3倍',
          value: 3
        },
        {
          name: '4倍',
          value: 4
        },
        {
          name: '5倍',
          value: 5
        },
      ],
      ossSign: {}
    }
  },
  onLoad(options) {
    if (options.token) {
      this.token = options.token
    }
    this.initData()

    this.getUploadUrl()
  },
  methods: {
    initData() {
      if (this.token) {
        this.setlogin()
      } else {
        this.getCidList()
      }
    },
    startTimeChange(e) {
      this.info.start_hours = e.detail.value
    },
    endTimeChange(e) {
      this.info.end_hours = e.detail.value
    },
    setlogin() {
      let that = this
      app.post('ApiIndex/logintogether', { gtksession: that.token }, function (res) {
        uni.setStorageSync('login_token', res.login_token)
        that.getCidList()
      })
    },
    gotoMapNearby() {
      uni.navigateTo({
        url: '/pages/openShop/mapNearby'
      })
    },
    //获取图片上传的oss地址
    getUploadUrl() {
      let that = this
      app.get('ApiImageupload/ossSign', {}, function (res) {
        if (res.status == 0) {
          that.ossSign = res.data
        } else {
          app.error(res.msg)
        }
      })
    },
    //获取主营类目列表
    getCidList() {
      let that = this
      app.get('ApiBusiness/apply', {}, function (res) {
        if (res.status === 2) {
          uni.redirectTo({
            url: '/admin/index/index'
          })
          return
        }

        let arr = res.clist.map(item => {
          let obj = { id: item.id, name: item.name }
          return obj
        })
        that.cateArr = arr
        that.cateName = that.cateArr[that.cindex]?.name

        that.info.id = res.info.id
        res.info.status !== null || undefined ? (that.BtnState = res.info.status) : (that.BtnState = null)

        if (that.BtnState >= 0) {
          that.info.linkman = res.info.linkman
          that.info.linktel = res.info.linktel
          that.info.name = res.info.name
          that.info.cid = res.info.cid
          that.info.start_hours = res.info.start_hours
          that.info.end_hours = res.info.end_hours
          that.info.address = res.info.address
          that.info.desc = res.info.desc
          that.info.id = res.info.id

          //提示驳回原因
          that.rejectTips = res.info.reason
          //图片反显
          that.zhengming = res.info.zhengming.split(',')
          that.pics = res.info.pics.split(',')
          that.pic = res.info.pic.split(',')
          that.info.zhengming = res.info.zhengming.split(',')
          that.info.pics = res.info.pics.split(',')
          that.info.pic = res.info.pic.split(',')
          // 让利比例
          that.info.ranglibili = res.info.ranglibili
          that.info.user_score_rate = Number(res.info.user_score_rate)

          let str = res.info.province + ',' + res.info.city + ',' + res.info.district + ',' + res.info.street
          that.multiStr = str
        }
        that.page_show = true
      })
    },
    //切换步骤
    handleNav(index) {
      if (this.BtnState !== null && this.BtnState !== undefined && this.BtnState !== 2) return
      //校验
      if (index == 1) {
        if (!this.checkOne()) return
      } else if (index == 2) {
        if (!this.checkOne()) return
        if (!this.checkTwo()) return
      }

      this.num = index
    },
    // 获取选择的地区
    handleGetRegions(obj) {
      let { addressData, multiStr } = obj
      this.addressData.province_id = addressData.province_id
      this.addressData.city_id = addressData.city_id
      this.addressData.area_id = addressData.area_id
      this.addressData.street_id = addressData.street_id
      this.multiStr = multiStr
    },
    //第一步校验
    checkOne() {
      let info = this.info
      if (info.name == '') {
        app.error('请填写商家名称')
        return false
      }
      if (info.linkman == '') {
        app.error('请填写联系人姓名')
        return false
      }
      if (info.linktel == '') {
        app.error('请填写联系人电话')
        return false
      }
      if (info.start_hours == '' || info.end_hours == '') {
        app.error('请选择营业时间')
        return false
      }
      // if (!uni.getStorageSync('SJDPposition')) {
      //   app.error('请选择店铺定位')
      //   return false
      // }
      return true
    },
    //第二步校验
    checkTwo() {
      if (this.zhengming.length < 3) {
        app.error('请上传营业执照、身份证正反面')
        return false
      }
      if (this.pic.length < 1) {
        app.error('请上传店铺门头照')
        return false
      }
      if (this.pics.length < 1) {
        app.error('请上传至少1张店铺实景')
        return false
      }
      return true
    },
    //第三步校验
    checkThree() {
      if (this.info.pwd == '' || this.info.repwd == '') {
        app.error('请确认密码')
        return false
      }
      if (this.info.pwd !== this.info.repwd) {
        app.error('两次密码输入不相同！')
        return false
      }
      return true
    },
    cateChange(e) {
      this.cindex = e.detail.value
      this.cateName = this.cateArr[this.cindex]?.name
      this.info.cid = this.cateArr[this.cindex]?.id
    },
    radioChange(e) {
      this.info.user_score_rate = this.radioList[e.detail.value]?.value
    },
    //
    ChooseImage(type, num) {
      let that = this
      uni.chooseImage({
        count: num || 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], //从相册选择
        success: res => {
          that.loading = true
          let tempFilePaths = res.tempFilePaths
          let tempFiles = res.tempFiles
          for (let i = 0; i < tempFilePaths.length; i++) {
            let randomName = new Date().getTime() + Math.round(Math.random() * 100) + tempFiles[i].name
            //上传图片
            uni.uploadFile({
              url: that.ossSign.host,
              filePath: tempFilePaths[i],
              formData: {
                key: that.ossSign.dir + randomName,
                OSSAccessKeyId: that.ossSign.accessid,
                policy: that.ossSign.policy,
                Signature: that.ossSign.signature,
                callback: that.ossSign.callback,
                success_action_status: 200
              },
              name: 'file',
              success: res => {
                that.loading = false
                // 地址+文件夹+文件名
                let str = that.ossSign.host + that.ossSign.dir + randomName
                switch (type) {
                  case 'one':
                    that.zhengming.push(str)
                    that.info.zhengming = that.zhengming.join(',')
                    break
                  case 'two':
                    that.pic.push(str)
                    that.info.pic = that.pic.join(',')
                    break
                  case 'three':
                    that.pics.push(str)
                    that.info.pics = that.pics.join(',')
                    break
                }
              }
            })
          }
        }
      })
    },
    // 预览图片
    ViewImage(type, index) {
      let urls = null
      switch (type) {
        case 'one':
          urls = this.zhengming
          break
        case 'two':
          urls = this.pic
          break
        case 'three':
          urls = this.pics
          break
      }
      uni.previewImg({
        urls,
        current: index
      })
    },
    DelImg(type, index) {
      switch (type) {
        case 'one':
          this.zhengming.splice(index, 1)
          break
        case 'two':
          this.pic.splice(index, 1)
          break
        case 'three':
          this.pics.splice(index, 1)
          break
      }
    },
    TimeChange(e) {
      this.time = e.detail.value
    },
    handleSubmit() {
      let that = this
      if (!that.checkThree()) return

      that.loading = true
      let info = that.info
      //#
      info.cash_ranglibili = info.ranglibili
      let arr = that.multiStr.split(',')
      info.province = arr[0]
      info.city = arr[1]
      info.district = arr[2]
      info.street = arr[3] || ''
      info.longitude = uni.getStorageSync('SJDPposition')?.longitude || ''
      info.latitude = uni.getStorageSync('SJDPposition')?.latitude || ''
      app.post('ApiBusiness/apply', { info }, function (res) {
        that.loading = false

        if (res.status == 1) {
          uni.showToast({
            title: res.msg,
            duration: 2000
          })
          setTimeout(() => {
            uni.navigateBack()
          }, 2000)
        } else {
          uni.showToast({
            icon: 'error',
            title: res.msg,
            duration: 2000
          })
          setTimeout(() => {
            uni.showToast({
              icon: 'error',
              title: '请点击对应步骤修改！',
              duration: 2000
            })
          }, 2000)
          return
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
// 导入colorUI
@import '/static/css/colorui/main.css';
@import '/static/css/colorui/icon.css';
.openShop-page {
  width: 100%;
  .cu-form-group .title {
    min-width: calc(4em + 15px);
  }
  .btn {
    width: 100%;
    display: flex;
    padding: 20upx 30upx;
    .flex1 {
      flex: 1;
    }
  }
  .wrap {
    display: flex;
  }
  .slider {
    width: 95%;
  }
  .sliderUnit {
    height: 78rpx;
    line-height: 78rpx;
    margin-left: -24rpx;
  }
  .rejectTips {
    background-color: white;
    padding: 0 30rpx 0;
    font-size: 32rpx;
  }
}
</style>
